package service

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type ConfirmarShopOrder struct {
	Address     models.MMemberAddress  `json:"address"`
	Pro         ShopProJson            `json:"pro"`
	Name        string                 `json:"name"`        //名称
	Logo        string                 `json:"logo"`        //logo
	Juan        decimal.Decimal        `json:"juan"`        //捐赠比例
	JuanName    string                 `json:"juan_name"`   //捐赠对象
	FreightList []models.MFreight      `json:"freight"`     //w物流信息
	CouponList  []models.MCouponRecord `json:"coupon_list"` //优惠券
	Region      []models.MRegion       `json:"region"`
}
type ShopProJson struct {
	Score             int             `json:"score"`             //可用积分
	LeveldkMoney      decimal.Decimal `json:"leveldk_money"`     //会员等级优惠金额
	Scoredkmaxpercent decimal.Decimal `json:"scoredkmaxpercent"` //积分抵扣:最多抵扣百分比
	Score2money       string          `json:"score2money"`       //积分抵扣:每积分抵扣
	Mjdata            string          `json:"mjdata"`            //满减信息
}

// 获取下单确认信息
func GetConfirmarShopOrder(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var returnData ConfirmarShopOrder
	//获取用户的下单地址
	var addressList []models.MMemberAddress
	err = models.DB.Model(new(models.MMemberAddress)).Where("mid=? AND aid=?", jsonData.Mid, jsonData.Aid).Find(&addressList).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断用户是否有收货地址
	if len(addressList) > 0 {
		cur := false
		//判断用户地址中是否有默认地址
		for _, v := range addressList {
			if v.Isdefault == 1 {
				returnData.Address = v
				cur = true
				break
			}
		}
		//如果没有默认地址，则选第一条地址
		if cur == false {
			returnData.Address = addressList[0]
		}
	}
	//获取商品信息
	var proData models.MShopProduct
	err = models.DB.Model(new(models.MShopProduct)).Where("id=?", jsonData.Id).First(&proData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	//获取用户信息
	var memberData models.MMember
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.Mid).First(&memberData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	//获取用户等级信息
	var LevelData models.MMemberLevel
	err = models.DB.Model(new(models.MMemberLevel)).Where("id=?", memberData.Levelid).First(&LevelData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		return
	}
	//获取系统设置
	var adminData models.MAdminSet
	err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", jsonData.Aid).First(&adminData).Error
	if err != nil {
		define.Response.ResultFail(c, 10005, define.JsonDataX, "")
		return
	}
	returnData.Name = adminData.Name
	returnData.Logo = adminData.Logo
	if proData.Scoredkmaxset == 0 {
		returnData.Pro.Score2money = adminData.ScoreMoney
		returnData.Pro.Scoredkmaxpercent = adminData.Scoredkmaxval
	} else if proData.Scoredkmaxset == 1 {
		returnData.Pro.Score2money = adminData.ScoreMoney
		returnData.Pro.Scoredkmaxpercent = proData.Scoredkmaxval
	} else if proData.Scoredkmaxset == 2 {
		returnData.Pro.Score2money = adminData.ScoreMoney
		returnData.Pro.Scoredkmaxpercent = proData.Scoredkmaxval
	} else if proData.Scoredkmaxset == -1 {
		returnData.Pro.Score2money = "0"
		returnData.Pro.Scoredkmaxpercent = decimal.NewFromFloat(0)
	}
	returnData.Pro.LeveldkMoney = LevelData.Discount
	returnData.Pro.Score = memberData.Score

	//获取物流信息
	if proData.Type == 2 {
		if proData.Freighttype == 1 {
			var freData []models.MFreight
			err = models.DB.Model(new(models.MFreight)).Where("aid=?", proData.Aid).First(&freData).Error
			if err != nil {
				define.Response.ResultFail(c, 10006, define.JsonDataX, "")
				return
			}
			returnData.FreightList = freData
		} else if proData.Freighttype == 0 {
			freigArr := strings.Split(proData.Freightdata, ",")
			for _, v := range freigArr {
				n, _ := strconv.Atoi(v)
				var freData models.MFreight
				err = models.DB.Model(new(models.MFreight)).Where("aid=? AND id=?", proData.Aid, n).First(&freData).Error
				if err != nil {
					define.Response.ResultFail(c, 10006, define.JsonDataX, "")
					return
				}
				returnData.FreightList = append(returnData.FreightList, freData)
			}
		}
	} else {
		newArr := strings.Split(proData.Freightdata, ",")
		for _, v := range newArr {
			var regionData models.MRegion
			num, _ := strconv.Atoi(v)
			err = models.DB.Model(new(models.MRegion)).Where("id=?", num).First(&regionData).Error
			if err != nil {
				define.Response.ResultFail(c, 10005, define.JsonDataX, "")
				return
			}
			returnData.Region = append(returnData.Region, regionData)
		}
	}
	//获取可用优惠券
	var couponData []models.MCouponRecord
	err = models.DB.Model(new(models.MCouponRecord)).Where("aid=? AND status=? AND mid=? AND type=?", jsonData.Aid, 0, jsonData.Mid, jsonData.Type).Find(&couponData).Error
	if err != nil {
		define.Response.ResultFail(c, 10007, define.JsonDataX, "")
		return
	}
	for _, v := range couponData {
		cur := false
		//是否是在使用的时间
		if time.Now().Unix() < int64(v.Usetime) {
			cur = true
		} else {
			continue
		}
		//判断商品是否可用
		var couData models.MCoupon
		err = models.DB.Model(new(models.MCoupon)).Where("id=?", v.Couponid).First(&couData).Error
		if err != nil {
			define.Response.ResultFail(c, 10007, define.JsonDataX, "")
			return
		}
		curFwtype := false
		if couData.Fwtype == 0 {
			curFwtype = true
		} else if couData.Fwtype == 1 { //判断栏目
			for _, m := range strings.Split(couData.Categoryids, ",") {
				n, _ := strconv.Atoi(m)
				if proData.CateId == n {
					curFwtype = true
					break
				}
				if proData.CateId2 == n {
					curFwtype = true
					break
				}
				if proData.CateId3 == n {
					curFwtype = true
					break
				}
				if proData.CateId4 == n {
					curFwtype = true
					break
				}
				if proData.CateId5 == n {
					curFwtype = true
					break
				}
				if proData.CateId6 == n {
					curFwtype = true
					break
				}
			}
		} else if couData.Fwtype == 2 { //判断商品
			for _, m := range strings.Split(couData.Productids, ",") {
				n, _ := strconv.Atoi(m)
				if n == proData.ID {
					curFwtype = true
					break
				}
			}
		}
		if curFwtype == true {
			cur = true
		} else {
			continue
		}
		//判断满足条件的优惠券
		if cur == true {
			returnData.CouponList = append(returnData.CouponList, v)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    returnData,
	})
}

type ShopOrderJson struct {
	Aid          int          `json:"aid"`           //账户ID
	Mid          int          `json:"mid"`           //会员ID
	AddressId    int          `json:"address_id"`    //地址id
	OrderType    int          `json:"order_type"`    //订单类型 1单件
	BusinessList BusinessList `json:"business_list"` //商品分类id
}
type BusinessList struct {
	Shop           []ShopGuiGe     `json:"shop"`
	Bid            int             `json:"bid"`             //
	Totalprice     decimal.Decimal `json:"totalprice"`      //总金额
	ProductPrice   decimal.Decimal `json:"product_price"`   //商品金额
	Score          int             `json:"score"`           //积分支付
	Type           string          `json:"type"`            //订单类型shop recharge
	FreightPrice   decimal.Decimal `json:"freight_price"`   //运费金额
	ScoredkMoney   decimal.Decimal `json:"scoredk_money"`   //积分抵扣金额
	Scoredkscore   int             `json:"scoredkscore"`    //积分抵扣用掉的积分
	InvoiceMoney   decimal.Decimal `json:"invoice_money"`   //发票金额
	LeveldkMoney   decimal.Decimal `json:"leveldk_money"`   //会员等级优惠金额
	ManjianMoney   decimal.Decimal `json:"manjian_money"`   //满减优惠金额
	CouponMoney    decimal.Decimal `json:"coupon_money"`    //优惠券金额
	CouponRid      string          `json:"coupon_rid"`      //优惠券coupon_record的id
	FreightDataval string          `json:"freight_dataval"` //备注
	FreightId      int             `json:"freight_id"`      //物流id
	FreightName    string          `json:"freight_name"`    //物流名称
	FreightType    int             `json:"freight_type"`    //配送方式类型 0普通快递 1到店自提 2同城配送 3自动发货 4在线卡密
	Platform       string          `json:"platform"`        //来源平台 mp公众号 wx微信小程序
}
type ShopGuiGe struct {
	Proid              int             `json:"proid"`                //商品id
	Name               string          `json:"name"`                 //商品名称
	GuigeId            int             `json:"guige_id"`             //规格ID
	Sum                int             `json:"sum"`                  //购买数量
	Totalprice         decimal.Decimal `json:"totalprice"`           //总价
	TotalWeight        decimal.Decimal `json:"total_weight"`         //总重量
	ScoredkMoney       decimal.Decimal `json:"scoredk_money"`        //积分抵扣金额
	LeveldkMoney       decimal.Decimal `json:"leveldk_money"`        //等级价格
	ManjianMoney       decimal.Decimal `json:"manjian_money"`        //满减金额
	CouponMoney        decimal.Decimal `json:"coupon_money"`         //优惠券金额
	RealTotalprice     decimal.Decimal `json:"real_totalprice"`      //实际商品销售金额 减去了优惠券抵扣会员折扣满减积分抵扣的金额
	BusinessTotalMoney decimal.Decimal `json:"business_total_money"` //商户总价
}
type ShopJsonList struct {
	Orderid    int    `json:"orderid"`    //订单Id
	Ordernum   string `json:"ordernum"`   //支付的接口路由
	Payorderid int    `json:"payorderid"` //订单支付表id
}

// 创建订单商城订单
func AddShopOrder(c *gin.Context) {
	var jsonData ShopOrderJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//获取系统设置
	var adminData models.MAdminSet
	err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", jsonData.Aid).First(&adminData).Error
	if err != nil {
		define.Response.ResultFail(c, 10010, define.JsonDataX, "")
		return
	}
	//获取用户的下单地址
	var addressData models.MMemberAddress
	err = models.DB.Model(new(models.MMemberAddress)).Where("id=? AND aid=?", jsonData.AddressId, jsonData.Aid).First(&addressData).Error
	if err != nil {
		define.Response.ResultFail(c, 10011, define.JsonDataX, "")
		return
	}
	//获取用户信息
	var memberData models.MMember
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.Mid).First(&memberData).Error
	if err != nil {
		define.Response.ResultFail(c, 10012, define.JsonDataX, "")
		return
	}
	var list []ShopJsonList
	tx := models.DB.Begin() //开启事务
	//生成订单号

	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    list,
	})
}
